import csv
import os
from abc import ABC, abstractmethod

# 常量定义
AI_ICON = "🤖"
ONLINE_ICON = "🟢"
OFFLINE_ICON = "🔴"
SUCCESS_ICON = "✅"
ERROR_ICON = "❌"
DATA_FILE = "ai_assistants_data.csv"
MAX_SIZE = 20


class AIAssistant(ABC):
    """AI助手抽象父类，定义所有助手的通用属性和抽象方法"""
    
    def __init__(self, aid, name, version, is_online, ability_score, type_):
        self.aid = aid  # 使用aid避免与内置id冲突
        self.name = name
        self.type = type_
        self.version = version
        self.is_online = is_online
        self.ability_score = ability_score

    @abstractmethod
    def show_sub_info(self):
        """展示子类特有属性"""
        pass

    # Getter和Setter方法
    @property
    def aid(self):
        return self._aid

    @aid.setter
    def aid(self, value):
        self._aid = value

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        self._name = value

    @property
    def type(self):
        return self._type

    @type.setter
    def type(self, value):
        self._type = value

    @property
    def version(self):
        return self._version

    @version.setter
    def version(self, value):
        self._version = value

    @property
    def is_online(self):
        return self._is_online

    @is_online.setter
    def is_online(self, value):
        self._is_online = value

    @property
    def ability_score(self):
        return self._ability_score

    @ability_score.setter
    def ability_score(self, value):
        if 0 <= value <= 100:
            self._ability_score = value


class DataAnalysisAssistant(AIAssistant):
    """数据分析助手（子类）"""
    
    def __init__(self, aid, name, version, is_online, ability_score, supported_formats):
        super().__init__(aid, name, version, is_online, ability_score, "数据分析助手")
        self.supported_formats = supported_formats

    def show_sub_info(self):
        print(f"【子类特有属性】支持的数据格式：{self.supported_formats}")

    @property
    def supported_formats(self):
        return self._supported_formats

    @supported_formats.setter
    def supported_formats(self, value):
        self._supported_formats = value


class ImageGenerationAssistant(AIAssistant):
    """图片生成助手（子类）"""
    
    def __init__(self, aid, name, version, is_online, ability_score, max_resolution):
        super().__init__(aid, name, version, is_online, ability_score, "图片生成助手")
        self.max_resolution = max_resolution

    def show_sub_info(self):
        print(f"【子类特有属性】最大生成分辨率：{self.max_resolution}")

    @property
    def max_resolution(self):
        return self._max_resolution

    @max_resolution.setter
    def max_resolution(self, value):
        self._max_resolution = value


class TextGenerationAssistant(AIAssistant):
    """文本生成助手（子类）"""
    
    def __init__(self, aid, name, version, is_online, ability_score, supported_text_types):
        super().__init__(aid, name, version, is_online, ability_score, "文本生成助手")
        self.supported_text_types = supported_text_types

    def show_sub_info(self):
        print(f"【子类特有属性】支持的文本类型：{self.supported_text_types}")

    @property
    def supported_text_types(self):
        return self._supported_text_types

    @supported_text_types.setter
    def supported_text_types(self, value):
        self._supported_text_types = value


class VoiceAssistant(AIAssistant):
    """语音助手（子类）"""
    
    def __init__(self, aid, name, version, is_online, ability_score, recognition_accuracy):
        super().__init__(aid, name, version, is_online, ability_score, "语音助手")
        self.recognition_accuracy = recognition_accuracy

    def show_sub_info(self):
        print(f"【子类特有属性】语音识别准确率：{self.recognition_accuracy}%")

    @property
    def recognition_accuracy(self):
        return self._recognition_accuracy

    @recognition_accuracy.setter
    def recognition_accuracy(self, value):
        self._recognition_accuracy = value


class TranslationAssistant(AIAssistant):
    """翻译助手（子类）"""
    
    def __init__(self, aid, name, version, is_online, ability_score, supported_languages_count):
        super().__init__(aid, name, version, is_online, ability_score, "翻译助手")
        self.supported_languages_count = supported_languages_count

    def show_sub_info(self):
        print(f"【子类特有属性】支持的语言数量：{self.supported_languages_count}种")

    @property
    def supported_languages_count(self):
        return self._supported_languages_count

    @supported_languages_count.setter
    def supported_languages_count(self, value):
        self._supported_languages_count = value


class AIManager:
    """AI助手管理器，实现所有核心业务逻辑"""
    
    def __init__(self):
        self.assistants = []  # 存储AI助手的列表
        self.load_data()  # 启动时加载数据

    def load_data(self):
        """加载保存的AI助手数据"""
        if not os.path.exists(DATA_FILE):
            return

        try:
            with open(DATA_FILE, 'r', encoding='utf-8') as f:
                reader = csv.reader(f)
                for row in reader:
                    if not row or len(row) < 6:
                        continue
                    
                    # 解析基础属性
                    type_ = row[0]
                    aid = row[1]
                    name = row[2]
                    version = row[3]
                    is_online = row[4] == "1"
                    ability_score = int(row[5])

                    # 根据类型创建对应子类实例
                    assistant = None
                    if type_ == "语音助手" and len(row) >=7:
                        accuracy = float(row[6])
                        assistant = VoiceAssistant(aid, name, version, is_online, ability_score, accuracy)
                    elif type_ == "文本生成助手" and len(row) >=7:
                        assistant = TextGenerationAssistant(aid, name, version, is_online, ability_score, row[6])
                    elif type_ == "图片生成助手" and len(row) >=7:
                        assistant = ImageGenerationAssistant(aid, name, version, is_online, ability_score, row[6])
                    elif type_ == "数据分析助手" and len(row) >=7:
                        assistant = DataAnalysisAssistant(aid, name, version, is_online, ability_score, row[6])
                    elif type_ == "翻译助手" and len(row) >=7:
                        lang_count = int(row[6])
                        assistant = TranslationAssistant(aid, name, version, is_online, ability_score, lang_count)

                    if assistant and len(self.assistants) < MAX_SIZE:
                        self.assistants.append(assistant)
            
            print(f"✅ 已加载保存的{len(self.assistants)}个AI助手数据")
        except Exception as e:
            print(f"❌ 加载数据失败：{str(e)}")

    def save_data(self):
        """保存AI助手数据到文件"""
        try:
            with open(DATA_FILE, 'w', encoding='utf-8', newline='') as f:
                writer = csv.writer(f)
                for assistant in self.assistants:
                    # 基础属性
                    row = [
                        assistant.type,
                        assistant.aid,
                        assistant.name,
                        assistant.version,
                        "1" if assistant.is_online else "0",
                        str(assistant.ability_score)
                    ]
                    
                    # 添加子类特有属性
                    if isinstance(assistant, VoiceAssistant):
                        row.append(str(assistant.recognition_accuracy))
                    elif isinstance(assistant, TextGenerationAssistant):
                        row.append(assistant.supported_text_types)
                    elif isinstance(assistant, ImageGenerationAssistant):
                        row.append(assistant.max_resolution)
                    elif isinstance(assistant, DataAnalysisAssistant):
                        row.append(assistant.supported_formats)
                    elif isinstance(assistant, TranslationAssistant):
                        row.append(str(assistant.supported_languages_count))
                    
                    writer.writerow(row)
        except Exception as e:
            print(f"❌ 保存数据失败：{str(e)}")

    def add_assistant(self, assistant):
        """添加新AI助手"""
        if len(self.assistants) >= MAX_SIZE:
            print("❌ 系统容量不足，无法添加新助手！")
            return False
            
        if self.get_assistant_by_id(assistant.aid):
            print(f"❌ ID为【{assistant.aid}】的助手已存在！")
            return False
            
        self.assistants.append(assistant)
        self.save_data()
        return True

    def get_assistant_by_id(self, aid):
        """根据ID查询助手"""
        for assistant in self.assistants:
            if assistant.aid == aid:
                return assistant
        return None

    def show_all_assistants(self, online_icon, offline_icon):
        """查看所有AI助手列表（按ID排序）"""
        if not self.assistants:
            print("📭 当前系统中暂无AI助手！")
            return
            
        # 按ID排序
        sorted_assistants = sorted(self.assistants, key=lambda x: int(x.aid) if x.aid.isdigit() else x.aid)
        
        print("所有AI助手列表（按ID排序）：")
        for i, assistant in enumerate(sorted_assistants, 1):
            status_icon = online_icon if assistant.is_online else offline_icon
            status_text = "在线" if assistant.is_online else "离线"
            print(f"{i}. ID: {assistant.aid}, 名称: {assistant.name}, 类型: {assistant.type}, "
                  f"版本: {assistant.version}, 状态: {status_icon}({status_text}), 能力评分: {assistant.ability_score}")

    def update_assistant(self, aid, property_, value):
        """根据ID修改助手属性"""
        assistant = self.get_assistant_by_id(aid)
        if not assistant:
            print(f"❌ 未找到ID为【{aid}】的助手！")
            return False
            
        try:
            if property_.lower() == "name":
                assistant.name = value
            elif property_.lower() == "type":
                assistant.type = value
            elif property_.lower() == "version":
                assistant.version = value
            elif property_.lower() == "online":
                assistant.is_online = (value == "1")
            elif property_.lower() == "score":
                score = int(value)
                if 0 <= score <= 100:
                    assistant.ability_score = score
                else:
                    print("❌ 能力评分必须在0-100之间！")
                    return False
            else:
                print("❌ 不支持修改该属性（仅支持：name/type/version/online/score）！")
                return False
                
            self.save_data()
            print(f"✅ 助手【{aid}】修改成功！")
            return True
        except Exception as e:
            print(f"❌ 修改失败：{str(e)}")
            return False

    def delete_assistant(self, aid):
        """根据ID删除AI助手"""
        assistant = self.get_assistant_by_id(aid)
        if not assistant:
            print(f"❌ 未找到ID为【{aid}】的助手！")
            return False
            
        self.assistants.remove(assistant)
        self.save_data()
        print(f"✅ 助手【{assistant.name}】已删除。")
        return True

    def start_assistant(self, aid):
        """启动AI助手服务（设置为在线）"""
        assistant = self.get_assistant_by_id(aid)
        if not assistant:
            print(f"❌ 未找到ID为【{aid}】的助手！")
            return False
            
        if assistant.is_online:
            print(f"ℹ️  助手【{assistant.name}】已在运行（在线）。")
            return True
            
        assistant.is_online = True
        self.save_data()
        print(f"✅ 助手【{assistant.name}】已启动服务（在线）。")
        return True

    def stop_assistant(self, aid):
        """停止AI助手服务（设置为离线）"""
        assistant = self.get_assistant_by_id(aid)
        if not assistant:
            print(f"❌ 未找到ID为【{aid}】的助手！")
            return False
            
        if not assistant.is_online:
            print(f"ℹ️  助手【{assistant.name}】已处于停止状态（离线）。")
            return True
            
        assistant.is_online = False
        self.save_data()
        print(f"✅ 助手【{assistant.name}】已停止服务（离线）。")
        return True

    def assign_task(self, aid, task_content):
        """为AI助手分配任务"""
        assistant = self.get_assistant_by_id(aid)
        if not assistant:
            print(f"❌ 未找到ID为【{aid}】的助手！")
            return False
            
        if not assistant.is_online:
            print(f"❌ {assistant.name} 当前离线，无法执行任务。")
            return False
            
        print(f"✅ 已为【{assistant.name}】分配任务：{task_content}")
        print(f"ℹ️  任务执行结果：{self.generate_task_result(assistant, task_content)}")
        return True

    def generate_task_result(self, assistant, task):
        """模拟任务执行结果"""
        if assistant.type == "数据分析助手":
            return "已完成数据清洗与可视化，生成Excel报告。"
        elif assistant.type == "图片生成助手":
            return f"已根据需求生成{assistant.max_resolution}分辨率图片。"
        elif assistant.type == "文本生成助手":
            return f"已完成文本创作，符合【{assistant.supported_text_types}】类型要求。"
        elif assistant.type == "翻译助手":
            return f"已完成多语言翻译（支持{assistant.supported_languages_count}种语言）。"
        elif assistant.type == "语音助手":
            return f"已完成语音识别与响应（准确率{assistant.recognition_accuracy}%）。"
        else:
            return "任务执行完成。"

    def show_statistics(self, ai_icon):
        """显示系统统计信息"""
        if not self.assistants:
            print("📭 当前系统中暂无AI助手，无法统计信息！")
            return
            
        online_count = sum(1 for a in self.assistants if a.is_online)
        total_score = sum(a.ability_score for a in self.assistants)
        avg_score = total_score / len(self.assistants)
        
        print(f"{ai_icon} 系统统计信息：")
        print(f"总助手数: {len(self.assistants)}")
        print(f"在线助手数({online_count}): 1-在线状态")
        print(f"离线助手数({len(self.assistants) - online_count}): 0-离线状态")
        print(f"平均能力评分: {avg_score:.2f}")

    # 以下为供外部调用的交互方法
    def query_assistant_by_id(self, online_icon, offline_icon):
        aid = input("请输入要查询的助手ID: ").strip()
        assistant = self.get_assistant_by_id(aid)
        if not assistant:
            print(f"❌ 未找到ID为【{aid}】的助手！")
            return
            
        print(f"\n{online_icon} 助手详情：")
        print(f"ID: {assistant.aid}")
        print(f"名称: {assistant.name}")
        print(f"类型: {assistant.type}")
        print(f"版本: {assistant.version}")
        status = f"{online_icon}(1-在线)" if assistant.is_online else f"{offline_icon}(0-离线)"
        print(f"状态: {status}")
        print(f"能力评分: {assistant.ability_score}")
        assistant.show_sub_info()

    def update_assistant_interactive(self):
        aid = input("请输入要修改的助手ID: ").strip()
        assistant = self.get_assistant_by_id(aid)
        if not assistant:
            print(f"❌ 未找到ID为【{aid}】的助手！")
            return
            
        print("可修改的属性：name(名称)/type(类型)/version(版本)/online(状态)/score(能力评分)")
        property_ = input("请输入要修改的属性: ").strip()
        if property_.lower() == "online":
            value = input("请输入新值(1-在线,0-离线): ").strip()
        else:
            value = input("请输入新值: ").strip()
            
        self.update_assistant(aid, property_, value)

    def delete_assistant_interactive(self):
        aid = input("请输入要删除的助手ID: ").strip()
        self.delete_assistant(aid)

    def start_assistant_interactive(self):
        aid = input("请输入要启动的助手ID: ").strip()
        self.start_assistant(aid)

    def stop_assistant_interactive(self):
        aid = input("请输入要停止的助手ID: ").strip()
        self.stop_assistant(aid)

    def assign_task_interactive(self):
        aid = input("请输入要分配任务的助手ID: ").strip()
        task = input("请输入任务内容: ").strip()
        self.assign_task(aid, task)


class Main:
    """主程序类，处理用户交互"""
    
    def __init__(self):
        self.ai_manager = AIManager()
        self.initialize_sample_data()

    def initialize_sample_data(self):
        """初始化示例数据（如果没有加载到数据）"""
        if not self.ai_manager.assistants:
            self.ai_manager.add_assistant(VoiceAssistant("101", "小智", "v1.2", True, 85, 95.5))
            self.ai_manager.add_assistant(TextGenerationAssistant("102", "文小助", "v2.0", True, 92, "诗歌,散文,报告"))
            self.ai_manager.add_assistant(ImageGenerationAssistant("103", "图灵", "v1.5", False, 88, "2048x2048"))
            self.ai_manager.add_assistant(DataAnalysisAssistant("104", "数小析", "v1.0", True, 79, "CSV,Excel,JSON"))
            self.ai_manager.add_assistant(TranslationAssistant("105", "翻译精灵", "v2.1", False, 95, 20))

    def show_menu(self):
        """显示菜单"""
        print(f"\n========== {AI_ICON} AI助手管理器 ==========")
        print("1. 查看所有AI助手列表")
        print("2. 根据ID查询助手详情")
        print("3. 添加新的AI助手")
        print("4. 根据ID修改助手信息")
        print("5. 删除AI助手（按ID）")
        print("6. 启动AI助手服务")
        print("7. 停止AI助手服务")
        print("8. 为AI助手分配任务")
        print("9. 显示系统统计信息")
        print("0. 退出系统")
        print("===================================")

    def get_valid_choice(self):
        """获取有效的用户选择"""
        while True:
            try:
                choice = input("请选择操作: ").strip()
                if not choice:
                    print(f"{ERROR_ICON} 输入不能为空，请输入数字: ", end="")
                    continue
                choice_int = int(choice)
                if 0 <= choice_int <= 9:
                    return choice_int
                print(f"{ERROR_ICON} 请输入0-9之间的数字: ", end="")
            except ValueError:
                print(f"{ERROR_ICON} 输入无效，请输入数字: ", end="")

    def add_new_assistant(self):
        """添加新AI助手"""
        print(f"{AI_ICON} 添加新AI助手")
        aid = input("请输入ID: ").strip()
        
        if not aid:
            print(f"{ERROR_ICON} ID不能为空！")
            return
            
        if self.ai_manager.get_assistant_by_id(aid):
            print(f"{ERROR_ICON} ID已存在，请重新输入！")
            return
            
        name = input("请输入名称: ").strip()
        if not name:
            print(f"{ERROR_ICON} 名称不能为空！")
            return
            
        version = input("请输入版本号: ").strip()
        if not version:
            print(f"{ERROR_ICON} 版本号不能为空！")
            return
            
        # 处理在线状态
        is_online = False
        while True:
            online_input = input("是否在线？(1-是, 0-否): ").strip()
            if online_input == "1":
                is_online = True
                break
            elif online_input == "0":
                is_online = False
                break
            else:
                print(f"{ERROR_ICON} 输入无效，请输入1或0！")
        
        # 处理能力评分
        ability_score = 0
        while True:
            try:
                score_input = input("请输入能力评分(0-100): ").strip()
                if not score_input:
                    print(f"{ERROR_ICON} 评分不能为空！")
                    continue
                ability_score = int(score_input)
                if 0 <= ability_score <= 100:
                    break
                print(f"{ERROR_ICON} 评分必须在0-100之间！")
            except ValueError:
                print(f"{ERROR_ICON} 请输入有效的整数！")
        
        # 选择助手类型
        print("请选择助手类型：")
        print("1. 数据分析助手")
        print("2. 图像助手")
        print("3. 文本助手")
        print("4. 翻译助手")
        print("5. 语音助手")
        
        type_choice = 0
        while True:
            try:
                type_input = input("请选择(1-5): ").strip()
                if not type_input:
                    print(f"{ERROR_ICON} 输入不能为空，请输入数字: ", end="")
                    continue
                type_choice = int(type_input)
                if 1 <= type_choice <= 5:
                    break
                print(f"{ERROR_ICON} 请输入1-5之间的数字: ", end="")
            except ValueError:
                print(f"{ERROR_ICON} 输入无效，请输入数字: ", end="")
        
        # 创建对应类型的助手
        assistant = self.create_assistant_by_type(
            type_choice, aid, name, version, is_online, ability_score)
            
        if assistant:
            if self.ai_manager.add_assistant(assistant):
                print(f"{SUCCESS_ICON} {AI_ICON} 助手【{name}】添加成功！")
            else:
                print(f"{ERROR_ICON} 系统已满，无法添加新助手！")
        else:
            print(f"{ERROR_ICON} 创建助手失败！")

    def create_assistant_by_type(self, type_choice, aid, name, version, is_online, ability_score):
        """根据类型选择创建对应的助手实例"""
        try:
            if type_choice == 1:
                formats = input("请输入支持的数据分析格式(用逗号分隔): ").strip()
                if not formats:
                    print(f"{ERROR_ICON} 格式不能为空！")
                    return None
                return DataAnalysisAssistant(aid, name, version, is_online, ability_score, formats)
                
            elif type_choice == 2:
                resolution = input("请输入最大生成分辨率: ").strip()
                if not resolution:
                    print(f"{ERROR_ICON} 分辨率不能为空！")
                    return None
                return ImageGenerationAssistant(aid, name, version, is_online, ability_score, resolution)
                
            elif type_choice == 3:
                text_types = input("请输入支持的文本类型(用逗号分隔): ").strip()
                if not text_types:
                    print(f"{ERROR_ICON} 文本类型不能为空！")
                    return None
                return TextGenerationAssistant(aid, name, version, is_online, ability_score, text_types)
                
            elif type_choice == 4:
                lang_input = input("请输入支持的语言数量: ").strip()
                if not lang_input:
                    print(f"{ERROR_ICON} 语言数量不能为空！")
                    return None
                lang_count = int(lang_input)
                if lang_count <= 0:
                    print(f"{ERROR_ICON} 语言数量必须大于0！")
                    return None
                return TranslationAssistant(aid, name, version, is_online, ability_score, lang_count)
                
            elif type_choice == 5:
                acc_input = input("请输入语音识别准确率: ").strip()
                if not acc_input:
                    print(f"{ERROR_ICON} 准确率不能为空！")
                    return None
                accuracy = float(acc_input)
                if not (0 <= accuracy <= 100):
                    print(f"{ERROR_ICON} 准确率必须在0-100之间！")
                    return None
                return VoiceAssistant(aid, name, version, is_online, ability_score, accuracy)
                
            else:
                return None
        except ValueError:
            print(f"{ERROR_ICON} 输入格式错误，请检查您的输入！")
            return None

    def run(self):
        """运行主程序"""
        print(f"欢迎使用 {AI_ICON} AI助手管理器 v1.0")
        
        while True:
            self.show_menu()
            choice = self.get_valid_choice()
            
            if choice == 0:
                print(f"感谢使用，再见！{AI_ICON}")
                break
                
            # 处理用户选择
            if choice == 1:
                self.ai_manager.show_all_assistants(ONLINE_ICON, OFFLINE_ICON)
            elif choice == 2:
                self.ai_manager.query_assistant_by_id(ONLINE_ICON, OFFLINE_ICON)
            elif choice == 3:
                self.add_new_assistant()
            elif choice == 4:
                self.ai_manager.update_assistant_interactive()
            elif choice == 5:
                self.ai_manager.delete_assistant_interactive()
            elif choice == 6:
                self.ai_manager.start_assistant_interactive()
            elif choice == 7:
                self.ai_manager.stop_assistant_interactive()
            elif choice == 8:
                self.ai_manager.assign_task_interactive()
            elif choice == 9:
                self.ai_manager.show_statistics(AI_ICON)


if __name__ == "__main__":
    main = Main()
    main.run()